package com.test.interceptor;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author mr du
 * @date 2024年05月19日 下午10:03
 * @description: 实现日志追踪拦截器
 */
public class LogInterceptor implements HandlerInterceptor {

    /**
     * 定义日志追踪号
     */
    private static final String TRACE_ID = "TRACE_ID";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String taaceId = IdUtil.simpleUUID();
        //如果http请求头携带了日志追踪号则使用传递过来的，如果没有直接默认一个即可
        if (StrUtil.isNotBlank(request.getHeader(TRACE_ID))) {
            taaceId = request.getHeader(TRACE_ID);
        }
        MDC.put(TRACE_ID, taaceId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //在请求结束之后销毁日志跟踪号
        MDC.remove(TRACE_ID);
    }
}
